﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;

using zijian666.AnyExtensions;

namespace zijian666.ComponentModel.DataAnnotations;

/// <summary>
/// 仅允许指定的值
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class AllowAttribute : ValidationAttribute
{
	private readonly object[] _values;

	public AllowAttribute(params object[] values)
	{
		values = [.. values]; // 为了防止数据被修改
		if (values.Length == 0)
		{
			throw new ArgumentNullException(nameof(values));
		}
		_values = values;
        ErrorMessage = "字段 {0} 只能是 " + _values.Join(",");
	}

	public override bool IsValid(object value)
	{
		if (value is null)
		{
			return true;
		}
		foreach (var val in _values)
		{
			if (val.Equals(value))
			{
				return true;
			}
		}
		return false;
	}
}
